package ru.aslanov.schedule.server.gcalendar;

import com.google.gdata.data.calendar.CalendarEventEntry;
import com.google.gdata.data.calendar.CalendarEventFeed;
import ru.aslanov.schedule.model.GCalendar;
import ru.aslanov.schedule.model.GoogleCalendarSyncCalendar;
import ru.aslanov.schedule.model.Group;
import ru.aslanov.schedule.server.PMF;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Collection;
import java.util.List;
import java.util.logging.Logger;

/**
 * Created by IntelliJ IDEA.
 * Created: Jul 7, 2010 11:22:48 AM
 *
 * @author Sergey Aslanov
 */
public class GCalendarSyncCalendarTaskServlet extends HttpServlet {
    private static final Logger log = Logger.getLogger(GCalendarSyncCalendarTaskServlet.class.getName());

    @Override
    protected void service(HttpServletRequest request, HttpServletResponse httpServletResponse) throws ServletException, IOException {
        log.info("Executing gcal-sync-calendar task");

        final PersistenceManager pm = PMF.getThreadLocalPersistenceManager();
        
        final String scheduleKey = request.getParameter("schedule");
        try {
            final Query query1 = pm.newQuery(GoogleCalendarSyncCalendar.class, "scheduleKey == :s");
            Collection res = (Collection) query1.execute(scheduleKey);
            for (Object cal : res) {

                GoogleCalendarSyncCalendar syncCalendar = (GoogleCalendarSyncCalendar) cal;

                final GCalendar gCalendar = syncCalendar.getGCalendar().getObject(pm);
                final String calId = gCalendar.getCalendarId();

                log.info("Syncing calendar " + gCalendar.getName() + " (" + calId + ")");

                GCalendarConnectService calendarService = new GCalendarConnectService(scheduleKey);
                GCalendarSyncService gCalendarSyncService = new GCalendarSyncService();

                // Clearing calendar
                final CalendarEventFeed calendarEventFeed = calendarService.getEventsFeed(calId);
                final List<CalendarEventEntry> entries = calendarEventFeed.getEntries();
                log.info("To clear calendar " + calId + " (" + entries.size() + " events)");
                for (CalendarEventEntry eventEntry : entries) {
                    gCalendarSyncService.removeEvent(calId, eventEntry.getId(), null);
                }
                final Query query = pm.newQuery(Group.class, "schedule == :s && calendarKey == :cal");
                Collection groups = (Collection) query.execute(scheduleKey, gCalendar.getEncodedKey());
                int groupsCount = 0;
                for (Object o : groups) {
                    gCalendarSyncService.createGroupSchedules(pm, (Group) o, null);
                    groupsCount++;
                }
                log.info("To add " + groupsCount + " groups for calendar " + calId);
                query.close(groups);

                gCalendarSyncService.sendEvents(scheduleKey, false);

                pm.deletePersistent(syncCalendar);

            }

            GCalendarSyncService.enqueEventsSync(scheduleKey);
        } catch (Exception e) {
            log.log(java.util.logging.Level.SEVERE, "Sync error", e);
            if (scheduleKey != null)
                GCalendarSyncService.clearSyncQueue(pm, scheduleKey);

        }

    }
}
